package l.l.w.CodingInterviews;

/**
 * Created by Administrator on 2018/4/12.
 */
public class 左旋转字符串 {
    /**
     * 这样会占用额外的空间，占了两个！
     * @param str
     * @param n
     * @return
     */
    public String LeftRotateString1(String str, int n) {
        if(str == null || str.length() == 0 || n < 0 || n > str.length()) return str;
        return (str + str).substring(n, str.length() + n);
    }
    public String LeftRotateString(String str, int n) {
        if(str == null || str.length() == 0 || n < 0 || n > str.length()) return str;
        char[] chars = str.toCharArray();
        int i = 0, j = n - 1;
        for(; i <= j;){swap(chars, i++, j--);}
        for(i = n, j = str.length() - 1;i <= j;){swap(chars, i++, j--);}
        for(i = 0, j = str.length() - 1;i <= j;){swap(chars, i++, j--);}
        return new String(chars);
    }

    private void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }

    public static void main(String[] args) {
        String str = "1234567890";
        String result = new 左旋转字符串().LeftRotateString(str, 3);
        System.out.println(result);
    }
}
